
package com.group.controller;

import com.base.view.BaseResult;
import com.base.view.GeneralResult;
import com.base.view.ListResult;
import com.group.model.*;
import com.group.util.NoteException;
import com.group.util.WeiXinUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 币相关接口
 *
 * @author zhaolei
 */
@Controller
public class TickerController extends BaseController {

	/**
	 * 查询币的列表
	 *
	 * @param key
	 * @param start
	 * @param limit
	 * @return
	 */
	@GetMapping("/ticker/query")
	@ResponseBody
	public ListResult<Ticker> queryTicker(String key, Integer start, Integer limit) {
		if (start == null || limit == null) {
			throw new NoteException("分页参数错误");
		}

		return new ListResult<Ticker>().setList(tickerDao.queryTicker(key, start, limit)).setTotal(tickerDao.queryTickerCount(key));
	}

	/*@GetMapping("/ticker/queryrate")
	@ResponseBody
	public ListResult<String> queryTickerRate(String key) {
		if (key == null) {
			throw new NoteException("参数错误");
		}
		String rate = beanDao.quickQueryOne(SystemPara.class, "name", "weccExchangeRate").getValue();
		return new GeneralResult<String>().setValue(rate);
	}*/

	/**
	 * 修改币的信息, 主要是头像
	 *
	 * @param ticker
	 * @return
	 */
	@PostMapping("/ticker/add")
	@ResponseBody
	public GeneralResult<Ticker> addTicker(@RequestBody Ticker ticker) {
		beanDao.add(ticker);

		return new GeneralResult<Ticker>().setValue(ticker);
	}

	/**
	 * 查询画图用的节点
	 *
	 * @param cid:
	 *            ticker中的cid字段
	 * @return
	 */
	@GetMapping("/ticker/currencies")
	@ResponseBody
	public GeneralResult<String> queryCurrencies(String cid) {
		if (StringUtils.isEmpty(cid))
			throw new NoteException("cid 不能为空");

		CookieManager cm = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
		CookieHandler.setDefault(cm);

		TickerCurrency tc = beanDao.quickQueryOne(TickerCurrency.class, "cid", cid);

		// czr 直接返回
		if ("czr".equals(cid)) {
			return new GeneralResult<String>().setValue(tc.getContent());
		}

		Long now = System.currentTimeMillis();

		// 如果是1小时内的信息
		if (tc != null && (now - tc.getCreateTime().getTime() < 3600000)) {
			return new GeneralResult<String>().setValue(tc.getContent());
		}
		if (tc == null) {
			tc = new TickerCurrency();
		}

		// WeiXinUtils.get("https://api.coinmarketcap.com/v1/ticker/?convert=EUR&limit=1");

		// 获取最新的图表信息
		Long end = System.currentTimeMillis();
		Long start = end - 7l * 24l * 60l * 60l * 1000l;
		String url = "https://graphs2.coinmarketcap.com/currencies/" + cid + "/" + start + "/" + end;
		tc.setContent(WeiXinUtils.get(url));
		tc.setCid(cid);
		tc.setCreateTime(new Date());
		beanDao.save(tc);

		return new GeneralResult<String>().setValue(tc.getContent());
	}

	/**
	 * 查询k线图
	 *
	 * @param cid
	 *            第一个币
	 * @param cid2
	 *            第二个币
	 * @param frame
	 *            时间间隔
	 * @param exchange
	 *            交易所
	 * @return
	 */
	@GetMapping("/ticker/currencies/new")
	@ResponseBody
	public ListResult<ExchangeCandles> queryBitfinexCandles(String cid, String cid2, String frame, String exchange) {
		if (StringUtils.isEmpty(cid2) || StringUtils.isEmpty(cid) || StringUtils.isEmpty(frame) || StringUtils.isEmpty(exchange)) {
			throw new NoteException("cid2 , cid ,frame,exchange 都不能为空");
		}

		List<ExchangeCandles> clist = tickerDao.queryCandles(cid, cid2, frame, exchange, 0, 400);
		return new ListResult<ExchangeCandles>().setList(clist);
	}

	/**
	 * 成交量查询
	 *
	 * @param cid
	 * @param cid2
	 * @param exchange
	 *            交易所
	 * @param start
	 * @param limit
	 * @return
	 */
	@GetMapping("/ticker/trades/query")
	@ResponseBody
	public ListResult<ExchangeTrades> queryExchangeTrades(String cid, String cid2, String exchange, Integer start, Integer limit) {
		if (start == null || limit == null) {
			throw new NoteException("分页参数错误");
		}
		if (limit > 500)
			limit = 10;

		return new ListResult<ExchangeTrades>().setList(tickerDao.queryExchangeTrades(cid, cid2, exchange, start, limit)).setTotal(tickerDao.queryExchangeTradesCount(cid, cid2, exchange));
	}

	/**
	 * 查询深度图
	 *
	 * @param cid
	 * @param cid2
	 * @param exchange
	 *            交易所
	 * @return
	 */
	@GetMapping("/ticker/book/query")
	@ResponseBody
	public ListResult<ExchangeBooks> queryExchangeBooks(String cid, String cid2, String exchange) {
		ExchangeBooks para = new ExchangeBooks();
		para.setBaseAsset(cid);
		para.setQuoteAsset(cid2);
		para.setExchange(exchange);
		return new ListResult<ExchangeBooks>().setList(beanDao.queryList(para));
	}

	/**
	 * 查询交易所下的 不同交易对的价格
	 *
	 * @param cid
	 * @param cid2
	 * @param exchange
	 *            交易所
	 * @param key
	 *            关键词
	 * @param start
	 * @param limit
	 * @return
	 */
	@GetMapping("/ticker/price/query")
	@ResponseBody
	public ListResult<TickerPrice> queryTickerPrice(String cid, String cid2, String exchange, String key, Integer start, Integer limit) {
		if (start == null || limit == null) {
			throw new NoteException("分页参数错误");
		}
		if (limit > 500)
			limit = 10;

		if (key != null) {
			key = key.toUpperCase();
		}

		return new ListResult<TickerPrice>().setList(tickerDao.queryTickerPrice(cid, cid2, exchange, key, start, limit)).setTotal(tickerDao.queryTickerPriceCount(cid, cid2, exchange, key));
	}

	/**
	 * 查询收藏的行情列表
	 *
	 * @param start
	 * @param limit
	 * @param request
	 * @return
	 */
	@GetMapping("/ticker/price/my/query")
	@ResponseBody
	public ListResult<TickerPrice> queryMyTickerPrice(Integer start, Integer limit, HttpServletRequest request) {
		User user = getUser(request);
		long userId = user.getId();

		return new ListResult<TickerPrice>().setList(tickerDao.queryMyTickerPrice(userId, start, limit)).setTotal(tickerDao.queryMyTickerPriceCount(userId));
	}

	/**
	 * 收藏行情
	 *
	 * @param tickerPriceId
	 * @param request
	 * @return
	 */
	@GetMapping("/ticker/price/follow")
	@ResponseBody
	public BaseResult followTickerPrice(Long tickerPriceId, HttpServletRequest request) {
		User user = getUser(request);

		TickerPriceFollow tpf = new TickerPriceFollow();
		tpf.setUserId(user.getId());
		tpf.setTickerPriceId(tickerPriceId);
		beanDao.save(tpf);

		return new BaseResult();
	}

	/**
	 * 取消收藏行情
	 *
	 * @param tickerPriceId
	 * @return
	 */
	@GetMapping("/ticker/price/unfollow")
	@ResponseBody
	public BaseResult unfollowTickerPrice(Long tickerPriceId, HttpServletRequest request) {
		User user = getUser(request);

		TickerPriceFollow tpf = new TickerPriceFollow();
		tpf.setUserId(user.getId());
		tpf.setTickerPriceId(tickerPriceId);
		TickerPriceFollow exist = beanDao.queryOne(tpf);
		if (exist != null) {
			beanDao.quickDeleteById(TickerPriceFollow.class, exist.getId());
		}

		return new BaseResult();
	}

	/**
	 * 查询是否关注
	 *
	 * @param tickerPriceId
	 * @param request
	 * @return
	 */
	@GetMapping("/ticker/price/follow/query")
	@ResponseBody
	public GeneralResult<Boolean> isFollowTickerPrice(Long tickerPriceId, HttpServletRequest request) {
		User user = getUser(request);

		TickerPriceFollow tpf = new TickerPriceFollow();
		tpf.setUserId(user.getId());
		tpf.setTickerPriceId(tickerPriceId);
		TickerPriceFollow exist = beanDao.queryOne(tpf);
		if (exist != null) {
			return new GeneralResult<Boolean>().setValue(true);
		}

		return new GeneralResult<Boolean>().setValue(false);
	}

	/**
	 * 龙虎榜接口
	 *
	 * @param exchange
	 * @return
	 */
	@GetMapping("/ticker/tigerRank/query")
	@ResponseBody
	public ListResult<LongHuBang> queryLongHuBang(String exchange) {

		return new ListResult<LongHuBang>().setList(tickerDao.queryLongHuBang(exchange));
	}

	/**
	 * test
	 *
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/ticker/czr/test")
	@ResponseBody
	public GeneralResult<String> czrPriceTest() throws Exception {
		// scheduleService.updateCzr();
		return new GeneralResult<String>().setValue("aaa");
	}

	/**
	 * 将非小号数据存到数据库
	 *
	 * @param globalRate
	 *            占全球总市值
	 * @param flowRate
	 *            流通率
	 * @param underTakeRate
	 *            接手率
	 * @param timesTamp
	 *            插入日期
	 * @param symbol
	 *            币的符号
	 * @return
	 */
	@GetMapping("/ticker/currencychart/update")
	@ResponseBody
	public BaseResult updateCurrencyChart(String globalRate, Double flowRate, Double underTakeRate, Long timesTamp, String symbol) {
		if (StringUtils.isEmpty(symbol)) {
			throw new NoteException("symbol参数不能为空");
		}
		if (globalRate == null) {
			throw new NoteException("globalRate参数不能为空");
		}
		if (flowRate == null) {
			throw new NoteException("flowRate参数不能为空");
		}
		if (underTakeRate == null) {
			throw new NoteException("underTakeRate参数不能为空");
		}
		if (timesTamp == null) {
			throw new NoteException("timesTamp参数不能为空");
		}
		// 将前端传过来的毫秒转换为日期
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(timesTamp);
		Date date = c.getTime();
		// 设置对象属性参数
		CurrencyChart para = new CurrencyChart();
		para.setSymbol(symbol);
		para.setTimesTamp(date);
		// 根据对象来查询
		CurrencyChart currencyChart = beanDao.queryOne(para);
		// 当数据库中没有这条数据时，将这条数据插入数据库
		if (currencyChart == null) {
			// 实例化一个对想
			currencyChart = new CurrencyChart();
			// 设置符号
			currencyChart.setSymbol(symbol);
			// 设置流通率
			currencyChart.setFlowRate(flowRate);
			// 设置全球占比
			currencyChart.setGlobalRate(globalRate);
			// 设置接手率
			currencyChart.setUnderTakeRate(underTakeRate);
			// 设置时间戳
			currencyChart.setTimesTamp(date);
			// 保存到数据库
			beanDao.save(currencyChart);

		}

		return new BaseResult();
	}

	/**
	 * 将非小号数据取出给前端
	 *
	 * @param symbol
	 *            币的符号
	 * @return
	 */
	@GetMapping("/ticker/currencychart/query")
	@ResponseBody
	public ListResult<CurrencyChart> queryCurrencyChart(String symbol) {
		if (StringUtils.isEmpty(symbol)) {
			throw new NoteException("symbol参数不能为空");
		}

		return new ListResult<CurrencyChart>().setList(tickerDao.queryCurrencyChart(symbol));
	}

}
